var modelobj, contactStore;
Ext.ns('DbConnection');


var calculateDesiredWidth = function () {
    var viewWidth = Ext.Viewport.getWindowWidth();
    desiredWidth = Math.min(viewWidth, 400) - 10;
    return desiredWidth;
};

Ext.setup({
    tabletStartupScreen: 'tablet_startup.png',
    phoneStartupScreen: 'phone_startup.png',
    icon: 'icon.png',
    glossOnIcon: false,
    onReady: function () {

        var dbconnval = {
            dbName: "DietApp",
            dbDescription: "testdb"
        };

        //Ext.DbConnection = new Ext.Sqlite.Connection(dbconnval);
        Ext.DbConnection = Ext.create('Ext.Sqlite.Connection', dbconnval);



        Ext.define("UserActivitiesModel", {
            extend: "Ext.data.Model",

            config: {
                idProperty: 'uniqueid', // if we have field with name as id, conflicts happens with default idProperty(id) which always have value as ext-record-x
                clientIdProperty: 'id',
                fields: [
					{
					    name: 'ActivityName',
					    type: 'string'
					},
					{
					    name: 'unit',
					    type: 'int'
					},
					{
					    name: 'cals',
					    type: 'int'
					}
					,
					{
					    name: 'id',
					    type: 'int',
					    fieldOption: 'PRIMARY KEY'
					},
					{
					    name: 'modifyDate',
					    type: 'string'
					}
				],
                proxy: {
                    type: 'sqlitestorage',
                    dbConfig: {
                        tablename: 'UserActivity_table',
                        dbConn: Ext.DbConnection
                        //dbQuery 	: 'SELECT * FROM contact_table limit 0,1' //dbQuery only works with read operation
                    },
                    reader: {
                        type: 'array'
                    }
                }
            },
            writer: {
                type: 'array'
            }
        });

        Ext.define("UserInfoModel", {
            extend: "Ext.data.Model",
            config: {
                idProperty: 'uniqueid', // if we have field with name as id, conflicts happens with default idProperty(id) which always have value as ext-record-x
                clientIdProperty: 'id',
                fields: [
					{
					    name: 'firstName',
					    type: 'string'
					},
					{
					    name: 'age',
					    type: 'string'
					},
					{
					    name: 'height',
					    type: 'string'
					}
					,
					{
					    name: 'weight',
					    type: 'string'
					},
					{

					    name: 'sex',
					    type: 'int'
					},
					{

					    name: 'BMI',
					    type: 'int'
					}
					,
					{
					    name: 'id',
					    type: 'int',
					    fieldOption: 'PRIMARY KEY'
					},
					{
					    name: 'modifyDate',
					    type: 'string'

					}
				],
                validations:
				 [
					{ type: 'presence', name: 'firstName', message: "الاسم غير صحيح " },
					{ type: 'presence', name: 'height', message: "الطول غير صحيح " },
					{ type: 'presence', name: 'age', message: "العمر غير صحيح" },
					{ type: 'presence', name: 'weight', message: "الوزن  غير صحيح " },
					{ type: 'format', name: 'height', matcher: /[0-9]{1,4}/, message: "الطول غير صحيح " },
					{ type: 'format', name: 'age', matcher: /[0-9]{1,4}/, message: "العمر غير صحيح " },
					{ type: 'format', name: 'weight', matcher: /[0-9]{1,4}/, message: "الوزن غير صحيح " }

				],

                proxy: {
                    type: 'sqlitestorage',
                    dbConfig: {
                        tablename: 'UserInfo_table',
                        dbConn: Ext.DbConnection
                        //dbQuery 	: 'SELECT * FROM contact_table limit 0,1' //dbQuery only works with read operation
                    },
                    reader: {
                        type: 'array'
                    }
                }
            },
            writer: {
                type: 'array'
            }
        });

        var userActivityStore = Ext.create('Ext.data.Store', {
            model: 'UserActivitiesModel',
            autoLoad: true,
            listeners: {
                load: function (store, records, opts) {

                    var totalCalsSum = 0;
                    Ext.each(records, function (rec, i) {
                        totalCalsSum += parseInt(rec.data.cals);
                    });

                    Ext.getCmp('ActivitiesSummaryPanel').setData({ "totalCalsSum": totalCalsSum });

                }
            }
        });
        var userInformationStore = Ext.create('Ext.data.Store', {
            model: 'UserInfoModel',
            autoLoad: true,
            listeners: {
                load: function (store, records, opts) {



                    if (records.length == 0) {



                        var myNewRecord = {
                            sex: 1,
                            BMI: 0,
                            totalPosts: 1,
                            modifyDate: new Date(),
                            id: 1
                        }
                        var rec = Ext.create('UserInfoModel', myNewRecord).save();
                        userInformationStore.load();


                    } else {
                        Ext.Viewport.add(formEdit);
                        formEdit.setRecord(records[0]);
                        formDis.setData(records[0].data);
                        //formEdit.show();
                    }

                }
            }
        });

        Ext.regModel('ModelSearchFood', {
            fields: ['id', 'name', 'cal']
        });

        var StorSearchFood = new Ext.data.Store({
            model: 'ModelSearchFood',
            autoLoad: true,
            proxy: {
                type: 'ajax',
                url: 'Food.xml',
                reader: {
                    type: 'xml',
                    record: 'food',
                    root: 'foods'
                }
            }
        });


        var FoodListSave = function () {

            if (parseInt(Ext.getCmp('units').getValue()) == 0) {
                alert("الكمية غير صحيحية");
                return;
            }
            var rec = Ext.create('UserActivitiesModel');

            rec.data.ActivityName = searchFood.ActivRecord.data.name;
            var totalCals = parseInt(searchFood.ActivRecord.data.cal) * parseInt(Ext.getCmp('units').getValue());
            rec.data.cals = totalCals;
            rec.id = searchFood.ActivRecord.id;
            rec.data.unit = Ext.getCmp('units').getValue();
            var dt = new Date();
            var dateval = Ext.Date.format(dt, "Y-m-d H:i:s");
            rec.data.modifyDate = dateval;
            rec.save();
            userActivityStore.load();
            searchFood.pop();
        };



        var template = Ext.XTemplate.from(Ext.get('detail-template'));





        ///workout

        var workoutListSave = function () {

            if (parseInt(Ext.getCmp('units').getValue()) == 0) {
                alert("المدة  غير صحيحية");
                return;
            }
            var rec = Ext.create('UserActivitiesModel');

            rec.data.ActivityName = searchworkout.ActivRecord.data.name;
            var totalCals = parseInt(searchworkout.ActivRecord.data.cal) * parseInt(Ext.getCmp('units').getValue());
            rec.data.cals = -1 * totalCals;
            rec.id = searchworkout.ActivRecord.id;
            rec.data.unit = Ext.getCmp('units').getValue();
            var dt = new Date();
            var dateval = Ext.Date.format(dt, "Y-m-d H:i:s");
            rec.data.modifyDate = dateval;
            rec.save();
            userActivityStore.load();
            searchworkout.pop();
        };



        Ext.regModel('ModelSearchWorksout', {
            fields: ['id', 'name', 'cal']
        });

        var StorWorksout = new Ext.data.Store({
            model: 'ModelSearchWorksout',
            autoLoad: true,
            proxy: {
                type: 'ajax',
                url: 'workout.xml',
                reader: {
                    type: 'xml',
                    record: 'workout',
                    root: 'workouts'
                }
            }
        });


        var searchworkout = new Ext.NavigationView({
            hidden: true,
            navigationBar: {
                items: [
					{
					    xtype: 'button',
					    id: 'workousaveButton',
					    text: 'حفظ',
					    align: 'right',
					    ui: 'action',
					    handler: workoutListSave,
					    hidden: true
					}
				]
            },
            centered: true,
            modal: true,
           
            width: (Ext.os.is.Phone ? 300 : 500),
            height: (Ext.os.is.Phone ? 300 : 500),
                     hideOnMaskTap: true,
                     scroll: 'vertical',
            items: [
				{
				    xtype: 'list',
				    title: 'البحث عن تمارين رياضية',
				    itemTpl: '<span id="{id}" > {name} <span class="redtxt"> عدد السعرات  {cal}</span></span>',
				    store: StorWorksout,
				    singleSelect: true,
				    itemSelector: 'span.id',
				    onItemDisclosure: function (record, btn, index) {
				        searchworkout.ActivRecord = record;
				        searchworkout.push({
				            xtype: 'panel',
				            title: 'Activity',
				            html: template.apply(record.data),
				            styleHtmlContent: true,
				            items: [
								{ id: 'units',
								    xtype: 'numberfield',
								    label: 'المدة',
								    name: 'units'
								}
							]
				        })

				    }
				}
			],
            listeners: {
                push: function (v, item) {

                    v.down('#workousaveButton').show();
                },
                pop: function (v, item) {

                    v.down('#workousaveButton').hide()
                }
            }
        });


        ///workout


       //water
      
 var waterPanel=    Ext.create('Ext.Panel', {
            hidden: true,
            centered: true,
            modal: true,
       
            width: (Ext.os.is.Phone ? 300 : 600),
            height: (Ext.os.is.Phone ? 300 : 700),
            // height: 500,
            hideOnMaskTap: true,
            items: [
            {
                xtype: 'toolbar',
                docked: 'top',
                layout: {
                    align: 'center',
                    pack: 'center',
                    type: 'hbox'
                },
                items: [
                    {
                        xtype: 'label',
                        html: 'كمية الماء المستهلك '
                    }
                ]
            },
             {
              xtype: 'sliderfieldextended',
              name: 'slider_decimal',
              labelAlign: 'top',
              labelText: 'Slider (Decimal)',
              label: 'Slider (Decimal)',
              value: 3,
              minValue: 0,
              maxValue: 10,
              increment: 1,
			 label: 'كأس ماء'
            },
           
            {
                xtype: 'toolbar',
                docked: 'bottom',
                items: [
                    {
                        xtype: 'button',
                        text: 'حفظ'
                    }
                ]
            }
        ]
    });


//water
        //searchFood
        var searchFood = new Ext.NavigationView({
            hidden: true,
            navigationBar: {
                items: [
					{
					    xtype: 'button',
					    id: 'searchFoodsaveButton',
					    text: 'حفظ',
					    align: 'right',
					    ui: 'action',
					    handler: FoodListSave,
					    hidden: true
					}
				]
            },
            centered: true,
            modal: true,
          
            hideOnMaskTap: true,
            width: (Ext.os.is.Phone ? 200 : 500),
            height: (Ext.os.is.Phone ? 300 : 500),


            scroll: 'vertical',
            items: [
				{
				    xtype: 'list',
				    title: 'البحث عن طعام',
				    itemTpl: '<span id="{id}" > {name} <span class="redtxt"> عدد السعرات  {cal}</span></span>',
				    store: StorSearchFood,
				    singleSelect: true,
				    itemSelector: 'span.id',
				    onItemDisclosure: function (record, btn, index) {
				        searchFood.ActivRecord = record;
				        searchFood.push({
				            xtype: 'panel',
				            title: 'Activity',
				            html: template.apply(record.data),
				            styleHtmlContent: true,
				            items: [
								{ id: 'units',
								    xtype: 'numberfield',
								    label: 'الكمية بالغرام',
								    name: 'units'
								}
							]
				        })

				    }
				}
			],
            listeners: {
                push: function (v, item) {

                    v.down('#searchFoodsaveButton').show();
                },
                pop: function (v, item) {
                    v.down('#searchFoodsaveButton').hide();
                }
            }
        });


        //searchFood

        var BMIinfotable=Ext.create('Ext.Panel', {
    hidden: true,
      centered: true,
            modal: true,
            width: (Ext.os.is.Phone ? 300 : 600),
            height: (Ext.os.is.Phone ? 300 : 700),
               scrollable: true,
           items:[      {
                xtype: 'toolbar',
                docked: 'top',
                layout: {
                    align: 'center',
                    pack: 'center',
                    type: 'hbox'
                },
                items: [
                    {
                        xtype: 'label',
                        html: 'مقياس كتلة الجسم  '
                    }
                ]
            }],
				    html: Ext.get('BMITable').dom.innerHTML,
            hideOnMaskTap: true
            }
            )

        //create main panel
        var formEdit = Ext.create('Ext.form.Panel', {
            id: "userInfoForm",

            hidden: true,
            centered: true,
            modal: true,
          
            hideOnMaskTap: false,
             width: (Ext.os.is.Phone ? 300 : 500),
            height: (Ext.os.is.Phone ? 300 : 500),

            items: [
				{
				    xtype: 'fieldset',
				    docked: "top",
				    title: "تعديل معلومات المستخدم",
				    defaults: {
				        labelWidth: '40%'
				    },
				    items: [
						{
						    xtype: 'textfield',
						    label: 'الاسم',
						    required: true,
						    name: 'firstName'
						},
						{
						    xtype: 'hiddenfield',
						    name: 'id'
						},
						{
						    xtype: 'textfield',
						    label: 'العمر',
						    name: 'age',
						    minValue: 18,
						    required: true,
						    maxValue: 150
						},
						{
						    xtype: 'textfield',
						    label: '  الطول',
						    required: true,
						    name: 'height'
						},
						{
						    xtype: 'textfield',
						    label: 'الوزن',
						    name: 'weight',
						    required: true
						},
						{
						    xtype: 'selectfield',
						    label: 'الجنس',
						    name: 'sex',
						    valueField: 'rank',
						    displayField: 'title',
						    store: {
						        data: [
									{ rank: '1', title: 'رجل' },
									{ rank: '0', title: 'امرأة' }

								]
						    }
						}
					]
				},
				{
				    "xtype": "toolbar",
				    docked: "bottom",
				    "items": [

						{
						    xtype: 'button',

						    id: "save",
						    text: 'حفظ',

						    handler: function () {
						        var userInfoFormCmp = Ext.getCmp('userInfoForm');


						        var UserInfoModel1 = Ext.ModelMgr.create(userInfoFormCmp.getValues(), 'UserInfoModel');

						        var errors = UserInfoModel1.validate(), message = "";
						        if (errors.isValid()) {
						            var dt = new Date();
						            var dateval = Ext.Date.format(dt, "Y-m-d H:i:s");
						            UserInfoModel1.data.modifyDate = dateval;
						            var weight = parseInt(UserInfoModel1.data.weight, 10);
						            var height = parseInt(UserInfoModel1.data.height, 10) / 100;
						            var bmi = Math.round(10 * weight / Math.pow(height, 2)) / 10;
						            UserInfoModel1.data.BMI = bmi


						            var rec = Ext.create('UserInfoModel', UserInfoModel1.data, UserInfoModel1.data.id).save();
						            userInformationStore.load();
						            formEdit.hide();
						        }
						        else {
						            Ext.each(errors.items, function (rec, i) {
						                message += rec._message + "<br>";
						            });
						            Ext.Msg.alert("Validate", message, function () { });
						            return false;
						        }




						    }
						}
						,
						{
						    xtype: 'button',

						    id: "",

						    handler: function () {
						        formEdit.hide();
						    },
						    text: 'الغاء'
						}
				    /////////
					]
				}


			]
        });

        formDis = new Ext.Panel({
            width: "50%",
            centered: true,
            tpl: Ext.XTemplate.from(Ext.get('BasicUserInof'))


        })

        var introPanel = Ext.create('Ext.Panel', {
            fullscreen: true,

            items: [
			{
			    xtype: 'panel',
			    height: 201,
			    html: Ext.get('introdiv').dom.innerHTML,

			    ui: 'dark'
			},
			{
			    xtype: 'button',
			    docked: 'bottom',
			    ui: 'confirm-round',
			    text: 'اهلاً وسهلاً',
			    handler: function () {
			        mainPanel.show();
			        introPanel.hide();

			    }
			}
		]


        })
        var mainPanel = Ext.create('Ext.TabPanel', {
            fullscreen: true,
            hidden: true,
             layout: {
            animation: 'fade',
            type: 'card'
        },
            tabBarPosition: 'Top',
            tabBar: {
                docked: 'top'
            },
            items: [
				{
				    xtype: 'container',
				    title: 'ملفك',
				    items: [formDis,
						{
						    "xtype": "toolbar",
						    "docked": "bottom",
						    "items": [
								{
								    xtype: 'button',
								    id: "edit",
								    text: 'تحرير',

								    handler: function () {


								        formEdit.show();
								    }
								},
                                {
								    xtype: 'button',
								    id: "oi",
								    text: 'كتلة الجسم',

								    handler: function () {
                                     Ext.Viewport.add(BMIinfotable);
                                       BMIinfotable.show();
								    }
								}
						    /////////
							]
						}


					]
				},
				{
				    xtype: 'formpanel',
				    ui: '',
				    layout: {
				        type: 'card'
				    },
				    title: 'نشاطاتك',
				    items: [
						{
						    xtype: 'toolbar',
						    docked: 'bottom',
						    layout: {
						        align: 'center',
						        type: 'hbox'
						    },
						    items: [
								{
								    xtype: 'button',
								    ui: 'action',
								    text: 'الطعام',
								    handler: function () {
								        Ext.Viewport.add(searchFood)
								        searchFood.show();
								    }


								},

								{
								    xtype: 'button',
								    ui: 'action',
								    text: 'رياضة',
								    handler: function () {
								        Ext.Viewport.add(searchworkout)
								        searchworkout.show();
								    }
								},
                                {
								    xtype: 'button',
								    ui: 'action',
								    text: 'ماء',
								    handler: function () {
								        Ext.Viewport.add(waterPanel)
								        waterPanel.show();
								    }
								}
							]
						},
						{
						    xtype: 'list',
						    items: [
                                    {
                                        xtype: 'toolbar',
                                        docked: 'top',
                                        items: [
                                            {
                                                id: "ActivitiesSummaryPanel",
                                                tpl: Ext.XTemplate.from(Ext.get('ActivitiesSummaryPanelTemp')),
                                                xtype: 'panel',
                                                cls: "greenbox"
                                            }
                                        ]
                                    }
                                ],
						    store: userActivityStore,
						    emptyText: "لا يوجد  نشاطات لهذا اليوم",

						    itemTpl: Ext.XTemplate.from(Ext.get('list-template')),
						    listeners: {
						        itemtap: function (view, index, item, record, e) {

						            console.log(e);
						            if (e.getTarget(".delete")) {
						                var rec = view.getStore().getAt(index);


						                var user = Ext.create('UserActivitiesModel', {

						                    id: 4,

						                    modifyDate: "2012-03-03 01:11:19"
						                });


						               rec.destroy();
						              // view.getStore().removeRecord(rec);


						            }
						        }
						    }
						}
					]
				},
				{
				    xtype: 'panel',
				    title: 'الرجيم الجاهز  ',
				    scrollable: true,
				    html: Ext.get('readyDiet').dom.innerHTML
				},
				{
				    xtype: 'panel',
				    title: 'ملاحظات ',
				    scrollable: true,
				    "items": [
        {
            "xtype": "toolbar",
            "docked": "bottom",
            "layout": {
                "align": "stretchmax",
                "pack": "end",
                "type": "hbox"
            },
            "items": [
                {
                    "xtype": "button",
                    "docked": "left",
                    "text": "حفظ"
                }
            ]
        },
        {
            "xtype": "textareafield",
            "height": 419,
           
        }
    ]
				}

			],
            listeners: [
				{
				    fn: 'onMybuttonRelease',
				    event: 'release',
				    delegate: '#mybutton'
				}
			]
        });

    }
});